<template>
  <div class="grid-view" ref="gridView">
    <slot></slot>
  </div>
</template>

<script scoped>
export default {
   name: 'GridView',
   props: {
     cols: {
       type: Number,
       default: 2
     },
     hMargin: {
       type: Number,
       default: 0.16
     },
     vMargin: {
       type: Number,
       default: 0.16
     },
     itemSpace: {
       type: Number,
       default: 0.16
     },
     lineSpace: {
       type: Number,
       default: 0.16
     }
   },
  data() {
    return {
      info: {itemWidth: 2, cols: 2}
    }
  },
  mouted() {
    this.setLayout()
  },
  updated() {
    this.setLayout()
  },
  methods: {
    setLayout() {
      //获得grid-view元素，及其children
      let gridEl = this.$refs.gridView;
      let children = gridEl.children;
      //设置gridEl的内边距
      gridEl.style.padding = `${this.vMargin}rem ${this.hMargin}rem`
      //计算item的宽度
     console.log(gridEl.clientWidth /50);

      let itemWidth = (gridEl.clientWidth /50 - 2 * this.hMargin - (this.cols-1) * this.itemSpace) / this.cols;
      this.info.itemWidth = itemWidth
      this.info.cols=this.cols
      console.log(itemWidth);

      //给item元素设置宽度，上边距，右边距
      for(let i = 0; i < children.length; i++){
        let item = children[i];
        item.style.width = itemWidth + 'rem'
        if((i+1) % this.cols !== 0){
          item.style.marginRight=this.itemSpace + 'rem'
        }
        if(i >= this.cols){
          item.style.marginTop = this.lineSpace + 'rem'
        }
      }
    }
  }
}
</script>

<style lang='less' scoped>
  .grid-view {
    display: flex;
    flex-wrap: wrap;
    width:100%;
  }
</style>
